#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int cnd1 = 0;
int cnd2 = 0;
int n = 3;
int depth = 0;
pthread_mutex_t lk;
pthread_cond_t cv_p;
pthread_cond_t cv_c;
const static int MY_TIMES = 20;

void init()
{
    pthread_mutex_init(&lk, NULL);
    pthread_cond_init(&cv_p, NULL);
    pthread_cond_init(&cv_c, NULL);
}

void *produce(void * arg)
{
    for (int i = 0; i < MY_TIMES; ++i)
    {
        pthread_mutex_lock(&lk);
        while (!(depth < n))
        {
            pthread_cond_wait(&cv_p, &lk);
        }
        printf("(");
        depth++;
        pthread_cond_signal(&cv_c);
        pthread_mutex_unlock(&lk);
    }
}
void *consume(void * arg)
{
    for (int i = 0; i < MY_TIMES; ++i)
    {
        pthread_mutex_lock(&lk);
        while (!(depth > 0))
        {
            pthread_cond_wait(&cv_c, &lk);
        }
        printf(")");
        depth++;
        pthread_cond_signal(&cv_p);
        pthread_mutex_unlock(&lk);
    }
}

int main()
{
    init();
    pthread_t thead1, thead2;
    pthread_create(&thead1,NULL,consume,NULL);
    pthread_create(&thead2,NULL,produce,NULL);
    pthread_join(thead1,NULL);
    pthread_join(thead2,NULL);
    return EXIT_SUCCESS;
}